/**
 * @description Growth platform Ad components and track SDK.
 * @copyright qschou.com
 * @version 1.0.0
 * @update 2018 - 12 - 15, async load this SDK, avoid pending & delay
 * @update 2018-12-22， add __QiSd
 * @tudo 1 打点失败，目标打点；2 将多个广告样式分文件异步载入；3 接口返回数据判断；4 wiki；5再次封装；6添加注释
 */


~(function ($) {
  var tasks = []
  if ($) {
    if (!$.q) {
    // console.log('QscG has been defined', $.q);
      return;
    }
    tasks = $.q;
  }
var TRACK_EVENT = {
  EXPOSE:1,
  CLICK: 2
}
var TF_HOST = 'https://s.tf.qschou.com';
var CONFIG_HOST = 'https://api-grows.qschou.com';
function merge() {
  var res = {};
  for (var i=0; i<arguments.length; i++){
    var obj = arguments[i];
    for (var p in obj){
      res[p] = obj[p];
    }
  }
  return res;
}
function _QscG() {
  // 广告位dict
  this.adpDict = {};
  // 投放dict
  this.servingDict = {};
  this.exposuredArr = [];
}
_QscG.prototype.track = function (ac, rid){
  this.baseInfo.gid = localStorage.getItem('__QiSd');
  const serving = this.servingDict[rid];
  var params = merge(this.baseInfo, this.adpDict[serving.scene], serving);
  params.ac = ac;
  params.rid = rid;
  this.ajaxClient('POST', TF_HOST + '/glog/log/report', params)
}
_QscG.prototype.makeDict = function(detail) {
  var that = this;
  this.adpDict[detail.scene] = {
    index: detail.index,
    version: detail.version
  };
  detail.templates.forEach(function(n){
    that.servingDict[n.rid] = {
      index: n.index,
      item_id: n.item_id,
      sign: n.sign,
      scene: detail.scene
    }
  })

}
_QscG.prototype.getAdClient = function (data, callback) {
  var client = new XMLHttpRequest()
  var that = this;
  client.onload = function () {
    var resData = JSON.parse(client.response).data;
    var sceneMulti = data.scene instanceof Array;
    if (resData.templates) {
      resData.templates.forEach(function(v){
        that.makeDict(v);
      });
      callback && callback(sceneMulti ? resData.templates : resData.templates[0]);
      setTimeout(exposeHandler, 200);
      /* 遍历检查曝光
      resData.templates.forEach(function(adDetail){
        var ridElems = document.querySelectorAll('[data-grow-adp="'+adDetail.scene+'"] [data-grow-rid]');
        ridElems && Array.prototype.forEach.call(ridElems, function(n) {
          that.setExpose(n);
        });
      });
      */
    } else {
      // throw new Error('Do not have advertising info');
    }
  }
  data['userid'] = this.baseInfo['uid'];
  data['product'] = this.baseInfo['product'];

  var project_uuid = this.baseInfo['project_uuid'];
  if (project_uuid) {
    data['project_uuid'] = project_uuid;
  }

  var formData = '&__QiSd=' + localStorage.getItem('__QiSd')
  for (var key in data) {
    if (data.hasOwnProperty(key)) {
      formData += '&' + key + '=' + data[key]
    }
  }
  formData = formData.slice(1)
  client.open('POST', CONFIG_HOST + '/api/grow', true)
  client.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
  client.send(formData)
}

_QscG.prototype.ajaxClient = function (method, url, data) {
  var client = new XMLHttpRequest()
  /*
  client.onload = function () {
    // console.log('success%o', client.response)
  }
  */
  client.open(method, url, true)
  client.setRequestHeader("Content-type", "application/json")
  if (method === 'POST' && data) {
    client.send(JSON.stringify(data))
  } else {
    client.send()
  }
}
_QscG.prototype.setExpose = function (el) {
  var rid = el.dataset.growRid;
  if (rid && !~this.exposuredArr.indexOf(rid)) {
    var scene = this.servingDict[rid].scene;
    var adpWrapper = document.querySelector('[data-grow-adp="'+scene+'"]');
    
    if (!adpWrapper) return;
    
    var adpRect = adpWrapper.getBoundingClientRect();
    var servingRect = el.getBoundingClientRect();
    var screenRect = {
      left:0,
      right: document.documentElement.offsetWidth,
      top:0,
      bottom: document.documentElement.offsetHeight
    };
    if (intersectRect(servingRect, adpRect) && intersectRect(adpRect, screenRect)){
      this.exposuredArr.push(rid);
      _qscg.track(1, rid);
    }
  }
}


const _qscg = new _QscG();
const api = {
  init: function(opts) {
    _qscg.baseInfo = {
      product: opts.product,
      product_line: opts.product_line,
      spid: opts.pageId,
      sv: '0.1.0',
      uid: opts.uId,
      project_uuid: opts.project_uuid
    };
  },
  getAdp: function(adp, flow, callback) {
    _qscg.getAdClient({
      product: _qscg.baseInfo.product,
      scene: adp,
      userid: _qscg.baseInfo.uId,
      flow: flow
    }, callback);
  },
  track: function (actionId, params){
    // rid, item_id, sign, ac
    _qscg.track(actionId, params);

  },
  rawTrack: function (adp, flow, actionId, rid) {
    if (_qscg.servingDict[rid]) {
      _qscg.track(actionId, rid);
      return;
    }
    _qscg.getAdClient({
      product: _qscg.baseInfo.product,
      scene: adp,
      userid: _qscg.baseInfo.uId,
      flow: flow
    }, function(){
      _qscg.track(actionId, rid);
    });
  }
}
window.QscG = function() {
  /*
  if (api[arguments[0]]) {
    return api[arguments[0]].apply(this, Array.prototype.slice.call(arguments, 1));
  }
  */
  tasks.push(arguments);
  urgeTask(tasks);
}
// 不管了，递归了
function urgeTask(tasks) {
  var task = tasks.shift();
  if (task) {
    api[task[0]].apply(this, Array.prototype.slice.call(task, 1));
    urgeTask(tasks);
  }
}

~function __setQiSdGrow() {
  var host = 'https://passport.qschou.com'
  var originStr = 'grow' //对应修改
  var hd = document.getElementsByTagName('head')[0]
  if (!localStorage.__QiSd || localStorage.__QiSd === 'undefined') {
    var iframe = document.createElement('iframe')
    iframe.src = host + '/sdk/identity/uuid-' + originStr + '.html'
    iframe.style = 'display:none'
    hd.appendChild(iframe)
    iframe.onload = function () {
      iframe.contentWindow.postMessage({
        idHost: originStr
      }, host);
      window.addEventListener("message", function (e) {
        // console.log(e)
        if (e.origin === host && e.data.idHost === originStr) {
          localStorage.__QiSd = e.data.__QiSd
          urgeTask(tasks);      
          // hd.removeChild(iframe)
        }
      }, false);
    }
  } else {
    urgeTask(tasks);
  }
}()
//将载入前的配置信息执行一遍

function findServingNode(n) {
  if (!n){
    return null;
  }
  while(n.getAttribute && !n.getAttribute('data-grow-adp')) {
    if (n.getAttribute('data-grow-rid')){
      return n;
    }
    n = n.parentNode;
  }
  return null;
}
function intersectRect(a, b) {
  return !(a.left >= b.right || a.right <= b.left || a.top >= b.bottom || a.bottom <= b.top);
}
document.body.addEventListener('click', function(e) {
  var target = findServingNode(e.target);
  if (target) {
    _qscg.track(TRACK_EVENT.CLICK, target.dataset.growRid);
  }
}, true);
document.body.addEventListener('transitionend', function(e) {
  //判断当前的target是不是投放
  if (e.target.parentNode.hasAttribute('data-grow-adp')) {
    var rids = e.target.querySelectorAll('[data-grow-rid]');
    rids && Array.prototype.forEach.call(rids, function(n) {
      _qscg.setExpose(n);
    });
  } else if (e.target.hasAttribute('data-grow-rid')) {
    _qscg.setExpose(e.target);
  }
}, false);
/* 去抖函数
function debounce(idle, action){
  var last;
  return function(){
    var ctx = this, args = arguments;
    clearTimeout(last)
    last = setTimeout(function(){
      action.apply(ctx, args)
    }, idle)
  }
}*/
function exposeHandler() {
  var rids = document.querySelectorAll('[data-grow-rid]');
  rids && Array.prototype.forEach.call(rids, function(n) {
    _qscg.setExpose(n);
  });
};
setInterval(exposeHandler, 1000);

})(QscG);